(function($){
    var defaultOption = {
        url: '',
        type: 'GET',
        data: {},
        dataType: 'json',
        headers: {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
    };

    var callbacks = {
        success: $.noop,
        fail: function (data) {
            alert(data.message);
        },
        error: function () {
            alert("请求超时");
        },
        always: $.noop,
        before: $.noop
    };

    $.myAjax = {
        ErrorCode: {
            SUCCESS: 0,
            SYSTEM_REDIRECT: 302,
            SYSTEM_ERROR: 9901,
            FIELD_EXIST: 10006,
        },
        base: function (opts, callback) {
            var ajaxOption = $.extend({}, defaultOption, opts);
            if (ajaxOption.type.toUpperCase() == 'POST') {
                // 如果是POST提交，自动附带csrf token
                ajaxOption.data[$("[name=csrf-param]").attr("content")] = $("[name=csrf-token]").attr("content");
            }
            if (typeof callback == 'function') {
                callback = {
                    success: callback
                }
            }
            var cbks = $.extend({}, callbacks, callback);
            var _self = this;

            return $.ajax(ajaxOption).done(function (data) {
                cbks.before(data);
                if (data.state == _self.ErrorCode.SYSTEM_REDIRECT) {
                    // 服务器要求跳转
                    if (data.message) {
                        alert(data.message);
                    }
                    window.location.href = data.data;
                } else if (data.state !== _self.ErrorCode.SUCCESS) {
                    // 有错误
                    cbks.fail(data);
                } else {
                    cbks.success(data);
                }
            }).fail(cbks.error).always(cbks.always);
        },
        // 从表单提交
        form: function (form, callback) {
            var $form = $(form);
            var type = $form.attr('method') || 'POST';
            var ajaxUrl = $form.attr('action') || '';
            var formData = $form.serialize();
            return this.base({
                'url': ajaxUrl,
                'type': type,
                'data': formData
            }, callback);
        },
        // 从特殊的button提交
        button: function (button, callback) {
            var $button=$(button);
            // $button.button("loading");
            var type = $button.attr("ajax-type") || 'POST';
            var ajaxUrl = $button.attr("href") || '';

            var t=/^params-(.*)$/;
            var formData = {};
            $($button.get(0).attributes).each(function (k, v) {
                if(t.test(v.name)){
                    formData[t.exec(v.name)[1]] = v.value;
                }
            })
            return this.base({
                'url': ajaxUrl,
                'type': type,
                'data': formData
            }, callback);
        }
    }
})(jQuery);